package com.sdsy.quartz;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sdsy.domain.ContractAddress;
import com.sdsy.domain.TransferAccountsRecordDO;
import com.sdsy.service.TransferAccountsRecordService;
import com.sdsy.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.methods.response.*;
import org.web3j.utils.Numeric;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created by hp on 2018/4/20.
 */
public class WalletRecordThred implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(WalletRecordThred.class);
    private List<ContractAddress> logResultList;
    private CountDownLatch countDownLatch;
    private TransferAccountsRecordService transferAccountsRecordService;
    private final String transaction_path = "https://api.etherscan.io/api?module=transaction&action=gettxreceiptstatus&txhash=TXHASH&apikey=APIKEY";

    //    private Web3j web3j;
    private List<String> list;
    private String apikey;

    public WalletRecordThred(List<ContractAddress> logResultList, CountDownLatch countDownLatch, TransferAccountsRecordService transferAccountsRecordService, List<String> list, String apikey) {

        this.logResultList = logResultList;
        this.countDownLatch = countDownLatch;
        this.transferAccountsRecordService = transferAccountsRecordService;
//        this.web3j = web3j;
        this.list = list;
        this.apikey = apikey;

    }

    @Override
    public void run() {

        for (int i = 0, len = logResultList.size(); i < len; i++) {
            ContractAddress vo = logResultList.get(i);
            if (vo.getInput().length() == 138) {
                TransferAccountsRecordDO transferAccountsRecordDO = newWalletRecord(vo);
                if (!list.contains(transferAccountsRecordDO.getHash())) {
//                insert(transferAccountsRecordDO);
                    transferAccountsRecordService.insert(transferAccountsRecordDO);
                }
            }
        }
        countDownLatch.countDown();
    }

    /**
     * 封装钱包信息
     *
     * @param vo
     * @return
     */
    private TransferAccountsRecordDO newWalletRecord(ContractAddress vo) {


        TransferAccountsRecordDO walletRecord = new TransferAccountsRecordDO();


        long lt = new Long(vo.getTimeStamp()) * 1000L;
        Date date = new Date(lt);

        walletRecord.setCreateData(date);

        walletRecord.setFromAddress(vo.getFrom());
        walletRecord.setHash(vo.getHash());
        if (!SysUtil.isNull(vo.getBlockNumber())) {
            walletRecord.setBlockNumber(Long.parseLong(vo.getBlockNumber()));
        }

        walletRecord.setBlockHash(vo.getBlockHash());
        walletRecord.setInput(vo.getInput());
        walletRecord.setToAddress(getAddress(vo.getInput()));
        if (!SysUtil.isNull(vo.getNonce())) {
            walletRecord.setNonce(Long.parseLong(vo.getNonce()));
        }
        walletRecord.setValue(vo.getValue());
        String tradeNo = StringUtils.getTransOrderNo(CommTypeUtils.BizTypeCode.TRANSFER);
        walletRecord.setTradeNo(tradeNo);
        walletRecord.setNum(getNum(vo.getInput()));
        if (!SysUtil.isNull(vo.getTxreceipt_status())) {
            walletRecord.setTxreceiptStatus(Long.parseLong(vo.getTxreceipt_status()));
        }
        walletRecord.setStatus(0);

        return walletRecord;
    }


    /**
     * 获取转账的钱包地址
     */
    public String getAddress(String input)  {
        logger.info("==============input===================" + input);
        String input_ = "";
        if (!CommonUtil.isNull(input)) {
            input_ = "0x" + input.substring(34, 74);
        }
        return input_;

    }


    /**
     * 时间戳转日期
     */
    public String formateDate(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(Long.parseLong(time) * 1000L);
        String time_ = simpleDateFormat.format(date);
        return time_;

    }

    /**
     * 数量
     */
    public String getNum(String input) {
        logger.info("==============input===================" + input);
        BigDecimal bigDecimal = new BigDecimal(0);
        BigDecimal wei = new BigDecimal("100000");
        String c = "";
        if (!CommonUtil.isNull(input)) {
            String input_ = input.substring(74, input.length());
            bigDecimal = new BigDecimal(Numeric.decodeQuantity("0x" + input_));
            BigDecimal all = bigDecimal.divide(wei);
            c = all.stripTrailingZeros().toPlainString();
        }
        return c;
    }


    /**
     * 记录数据
     */
    public void insert(TransferAccountsRecordDO walletRecord) {

        String transaction_status = transaction_path.replace("TXHASH", walletRecord.getHash()).replace("APIKEY", apikey);
        String json = HttpClientUtil.doGet(transaction_status);

        /**
         {"status":"1","message":"OK","result":{"status":"1"}}
         */
        if (!SysUtil.isNull(json)) {
            JSONObject jsonObject = JSONUtil.parseObj(json);
            String result = jsonObject.getStr("result");
            JSONObject obj = JSONUtil.parseObj(result);
            String status = obj.getStr("status");
            /**状态 1-成功，0-失败**/
            if (SysUtil.isNull(status)) {
                status = "0";
            }
            walletRecord.setTxreceiptStatus(Long.parseLong(status));
            walletRecord.setStatus(0);
            transferAccountsRecordService.insert(walletRecord);
        } else {

            logger.info("insert方法数据为空==================================");
        }
    }

}
